package coreservlets.ch9;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShowItems extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String PREVIOUS_ITEMS_SESSION_KEY = "previousItems";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		@SuppressWarnings("unchecked")
		ArrayList<String> previousItems = (ArrayList<String>) session.getAttribute(PREVIOUS_ITEMS_SESSION_KEY);
		if (previousItems == null) {
			previousItems = new ArrayList<String>();
			session.setAttribute(PREVIOUS_ITEMS_SESSION_KEY, previousItems);
		}
		String newItem = req.getParameter("newItem");
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		String title = "Items Purchased";
		String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">\n";
		out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title
				+ "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>"
				+ title + "</H1>");
		synchronized (previousItems) {
			if (newItem != null) {
				previousItems.add(newItem);
			}
			if (previousItems.isEmpty()) {
				out.println("<I>No items<I/>");
			}else {
				out.println("<UL>");
				for (String item : previousItems) {
					out.println("<LI>" + item + "</LI>");
				}
				out.println("</UL>");
			}
		}
		out.println("</BODY></HTML>");
	}

}
